package com.baihui.taobao.db;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baihui.taobao.util.Util;
import com.baihui.taobao.vo.BTrade;
import com.taobao.api.TaobaoObject;

/**
 * Created by Kevin. User: HSZM1106-0312 Date: 12-1-14 Time: 下午5:41
 */
public class TradeDAO extends GeneDAO {
	@Override
	/**
	 * 返回主键id
	 */
	protected String getPrimaryKey(Class aClass) {
		return "tid";
	}

	@Override
	protected Class getDomainClass() {
		return BTrade.class;
	}

	@Override
	/**
	 * 处理关联属性
	 */
	protected String parseRelationType(Field field) {
		return null;
	}

	@Override
	/**
	 * 解析
	 */
	protected Object parseValue(Object value, Field field) {
		return value;
	}

	@Override
	public String[] getExcludefield() {
		return new String[] { "serialVersionUID", "promotionDetails", "orders",
				"baihuiid", "exported" };
	}

	@Override
	public Map<String, Object> findObject(String sql, Object[] params)
			throws Exception {
		Map<String, Object> map = super.findObject(sql, params);
		if (map.get("tid") != null) {
			// 装载物流信息
			ShippingDAO shippingDAO = new ShippingDAO();
			Map<String, Object> shipping = shippingDAO.findObject(
					"select * from tbshipping where tid= ? ",
					new Object[] { map.get("tid").toString() });
			if (shipping == null)
				shipping = new HashMap<String, Object>();
			map.put("shipping", shipping);
			// 装载购买产品信息
			// OrderDAO orderDAO = new OrderDAO();
			// L/ist<Map> orders =
			// orderDAO.findAllObject("select * from tborder where parent = " +
			// map.get("tid").toString());
			// map.put("orders", orders);
		}
		return map;
	}

	public Map<String, Object> findDate(String sql, Object[] params)
			throws Exception {
		Map<String, Object> map = super.findObject(sql, params);
		return map;
	}

	@Override
	public List<Map> findAllObject(String sql) throws Exception {
		List<Map> maps = super.findAllObject(sql);
		ShippingDAO shippingDAO = new ShippingDAO();
		for (Map map : maps) {
			if (map.get("tid") != null) {
				Map<String, Object> shipping = shippingDAO.findObject(
						"select * from tbshipping where tid= ? ",
						new Object[] { map.get("tid").toString() });
				if (shipping == null)
					shipping = new HashMap<String, Object>();
				map.put("shipping", shipping);
				// 装载购买产品信息
				// List<Map> orders =
				// orderDAO.findAllObject("select * from tborder where parent = "
				// + map.get("tid").toString());
				// map.put("orders", orders);
			}
		}
		return maps;
	}

	@Override
	public List<Map> findAllObject(String sql, Object[] params)
			throws Exception {
		List<Map> maps = super.findAllObject(sql, params);
//		ShippingDAO shippingDAO = new ShippingDAO();
//		for (Map map : maps) {
//			if (map.get("tid") != null) {
//				Map<String, Object> shipping = shippingDAO.findObject(
//						"select * from tbshipping where tid= ? ",
//						new Object[] { map.get("tid").toString() });
//				if (shipping == null)
//					shipping = new HashMap<String, Object>();
//				map.put("shipping", shipping);
//				// 装载购买产品信息
//				// List<Map> orders =
//				// orderDAO.findAllObject("select * from tborder where parent = "
//				// + map.get("tid").toString());
//				// map.put("orders", orders);
//			}
//		}
		return maps;
	}

	@Override
	public List<Map> findAllObject(String sql, int maxValue) throws Exception {
		List<Map> maps = super.findAllObject(sql, maxValue);
		ShippingDAO shippingDAO = new ShippingDAO();
		for (Map map : maps) {
			if (map.get("tid") != null) {
				Map<String, Object> shipping = shippingDAO.findObject(
						"select * from tbshipping where tid= ? ",
						new Object[] { map.get("tid").toString() });
				if (shipping == null)
					shipping = new HashMap<String, Object>();
				map.put("shipping", shipping);
				// 装载购买产品信息
				// List<Map> orders =
				// orderDAO.findAllObject("select * from tborder where parent = "
				// + map.get("tid").toString());
				// map.put("orders", orders);
			}
		}
		return maps;
	}

	@Override
	public void update(List<TaobaoObject> infos, Connection cn)
			throws Exception {
		if (infos == null || infos.size() <= 0)
			return;
		List<Object[]> values = new ArrayList<Object[]>();
		Object info = infos.get(0);
		Field[] descriptors = Util.getAllField(info.getClass());
		for (Object taobaoObject : infos) {
			if (info == null)
				info = taobaoObject;
			List<Object> tmp = constructValues((TaobaoObject) taobaoObject,
					descriptors, false);
			values.add(tmp.toArray(new Object[] {}));
		}

		updateAndInsert(cn, generateUpdateSql(info.getClass(), descriptors),
				values);
	}

	public String generateUpdateSql(Class domainClass, Field[] fields)
			throws Exception {
		try {
			String formateReg = "update {0} set {1} where {2}";

			String tableName = "T" + domainClass.getSimpleName();
			StringBuilder fieldParam = new StringBuilder();
			StringBuilder valueParam = new StringBuilder();

			for (int i = 0; i < fields.length; i++) {
				Field field = fields[i];
				if (Util.isExist(field.getName(), getExcludefield())) {
					continue;
				}
				if (field.getName().equals(getPrimaryKey(domainClass))) {
					continue;
				}
				// if (field.getName().equals("userId")) {
				// continue;
				// }
				if (field.getName().equals("id"))
					continue;
				if (i < fields.length - 1) {
					fieldParam.append(field.getName() + "=?,");
				} else {
					fieldParam.append(field.getName() + "=?");
				}
			}
			valueParam.append((getPrimaryKey(domainClass) == null ? "id"
					: getPrimaryKey(domainClass)) + "=?");
			MessageFormat format = new MessageFormat(formateReg);
			return format.format(new String[] { tableName,
					fieldParam.toString(), valueParam.toString() });
		} catch (Exception e) {
			throw e;
		}
	}

	public void insertTrade(List<BTrade> infos, Connection cn) throws Exception {
		if (infos == null || infos.size() <= 0)
			return;
		StringBuffer sql = new StringBuffer();
		sql.append(" insert into tbtrade(userId,adjustFee,alipayId,buyerAlipayNo,buyerArea,buyerEmail,buyerMemo, ");
		sql.append(" buyerMessage,buyerNick,created,discountFee,endTime,modified,payTime,payment,picPath,postFee,price, ");
		sql.append(" realPointFee,receivedPayment,receiverAddress,receiverCity,receiverDistrict,receiverMobile,receiverName,receiverPhone, ");
		sql.append(" receiverState,receiverZip,sellerEmail,sellerMemo,sellerMobile,sellerName,sellerNick,sellerPhone,shippingType, ");
		sql.append(" status,tid,timeoutActionTime,title,totalFee,tradeMemo,type,exported,baihuiid )values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,");
		sql.append(" ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

		List<Object[]> values = new ArrayList<Object[]>();
		for (BTrade trade : infos) {
			List<Object> tmp = new ArrayList<Object>();
			tmp.add(trade.getUserId());
			tmp.add(trade.getAdjustFee());
			tmp.add(trade.getAlipayId());
			tmp.add(trade.getBuyerAlipayNo());
			tmp.add(trade.getBuyerArea());
			tmp.add(trade.getBuyerEmail());
			tmp.add(trade.getBuyerMemo());
			tmp.add(trade.getBuyerMessage());
			tmp.add(trade.getBuyerNick());
			tmp.add(trade.getCreated());
			tmp.add(trade.getDiscountFee());
			tmp.add(trade.getEndTime());
			tmp.add(trade.getModified());
			tmp.add(trade.getPayTime());
			tmp.add(trade.getPayment());
			tmp.add(trade.getPicPath());
			tmp.add(trade.getPostFee());
			tmp.add(trade.getPrice());
			tmp.add(trade.getRealPointFee());
			tmp.add(trade.getReceivedPayment());
			tmp.add(trade.getReceiverAddress());
			tmp.add(trade.getReceiverCity());
			tmp.add(trade.getReceiverDistrict());
			tmp.add(trade.getReceiverMobile());
			tmp.add(trade.getReceiverName());
			tmp.add(trade.getReceiverPhone());
			tmp.add(trade.getReceiverState());
			tmp.add(trade.getReceiverZip());
			tmp.add(trade.getSellerEmail());
			tmp.add(trade.getSellerMemo());
			tmp.add(trade.getSellerMobile());
			tmp.add(trade.getSellerName());
			tmp.add(trade.getSellerNick());
			tmp.add(trade.getSellerPhone());
			tmp.add(trade.getShippingType());
			tmp.add(trade.getStatus());
			tmp.add(trade.getTid());
			tmp.add(trade.getTimeoutActionTime());
			tmp.add(trade.getTitle());
			tmp.add(trade.getTotalFee());
			tmp.add(trade.getTradeMemo());
			tmp.add(trade.getType());
			tmp.add(trade.getExported());
			tmp.add(trade.getBaihuiid());

			values.add(tmp.toArray(new Object[] {}));
		}

		updateAndInsert(cn, sql.toString(), values);
	}
	
	public void updateTrade(List<BTrade> infos, Connection cn) throws Exception {
		if (infos == null || infos.size() <= 0)
			return;
		StringBuffer sql = new StringBuffer();
		sql.append(" update tbtrade set exported = ?,status = ?,timeoutActionTime = ?,receiverAddress = ?,receiverCity = ?,receiverDistrict = ?,");
		sql.append(" receiverState = ?,receiverZip = ?,tradeMemo = ?,postFee = ?,buyerMessage = ?,receiverMobile = ?,payTime = ?,");
		sql.append(" endTime = ?,modified = ?,sellerMemo = ? ");
		sql.append(" where userId = ? and tid = ? ");

		List<Object[]> values = new ArrayList<Object[]>();
		for (BTrade trade : infos) {
			List<Object> tmp = new ArrayList<Object>();
			tmp.add(2);
			tmp.add(trade.getStatus());
			tmp.add(trade.getTimeoutActionTime());
			tmp.add(trade.getReceiverAddress());
			tmp.add(trade.getReceiverCity());
			tmp.add(trade.getReceiverDistrict());
			tmp.add(trade.getReceiverState());
			tmp.add(trade.getReceiverZip());
			tmp.add(trade.getTradeMemo());
			tmp.add(trade.getPostFee());
			tmp.add(trade.getBuyerMessage());
			tmp.add(trade.getReceiverMobile());
			tmp.add(trade.getPayTime());
			tmp.add(trade.getEndTime());
			tmp.add(trade.getModified());
			tmp.add(trade.getSellerMemo());
			tmp.add(trade.getUserId());
			tmp.add(trade.getTid());

			values.add(tmp.toArray(new Object[] {}));
		}

		updateAndInsert(cn, sql.toString(), values);
	}
}
